package com.fwtai.service.api;

import com.fwtai.api.ApiContractTemplateDao;
import com.fwtai.bean.PageFormData;
import com.fwtai.config.LocalUserId;
import com.fwtai.service.AsyncService;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolString;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 合同模板业务层
 */
@Service
public class ApiContractTemplateService{

  @Value("${upload_dir_window}")
  private String dir_window;

  @Value("${upload_dir_linux}")
  private String dir_linux;

  private final AsyncService asyncService;

  private final ApiContractTemplateDao apiContractTemplateDao;

  private final ApiContractOrderService apiContractOrderService;

  private final ThreadPoolTaskExecutor taskExecutor;

  public ApiContractTemplateService(final ApiContractTemplateDao apiContractTemplateDao,final ApiContractOrderService apiContractOrderService,final ThreadPoolTaskExecutor taskExecutor,final AsyncService asyncService){
    this.apiContractTemplateDao = apiContractTemplateDao;
    this.apiContractOrderService = apiContractOrderService;
    this.taskExecutor = taskExecutor;
    this.asyncService = asyncService;
  }

  public String queryById(final String kid){
    final String loginId = LocalUserId.get();
    return CompletableFuture.supplyAsync(() -> {
      if(kid == null || kid.length() <= 0){
        return ToolClient.jsonValidateField();
      }
      HashMap<String,Object> formData = new HashMap<String,Object>(2);
      formData.put("contractId",kid);
      formData.put("loginId",loginId);
      boolean b = apiContractOrderService.queryExist(formData);
      final HashMap<String,Object> contractData = apiContractTemplateDao.queryById(kid);
      contractData.put("purchased",b);
      return ToolClient.queryJson(contractData);
    },taskExecutor).join();
  }

  /**
   * 适用于api接口,仅含数据不含总记录数总条数,前端仅做返回的数据是否小于每页大小
   */
  public String listData(final HttpServletRequest request){
    return CompletableFuture.supplyAsync(() -> {
      final PageFormData formData = ToolClient.pageParamsApi(request);
      if(formData == null){
        return ToolClient.jsonValidateField();
      }
      return ToolClient.jsonPage(apiContractTemplateDao.getListData(formData));
    },taskExecutor).join();
  }

  public String getListById(final HttpServletRequest request){
    final String loginId = LocalUserId.get();
    return CompletableFuture.supplyAsync(() -> {
      final PageFormData formData = ToolClient.pageParamsApi(request);
      if(formData == null){
        return ToolClient.jsonValidateField();
      }
      final String userId = formData.getString("userId");
      if(userId == null || userId.length() <= 0){
        if(loginId == null){
          return ToolClient.accessLogin();
        }
        formData.put("userId",loginId);
      }
      return ToolClient.jsonPage(apiContractTemplateDao.getListById(formData));
    },taskExecutor).join();
  }

  //获取表contract_template的字段contract_type的下拉框列动态值选项的数据
  public String getContract_type(final Long kid){
    return CompletableFuture.supplyAsync(() -> ToolClient.queryJson(apiContractTemplateDao.getContract_type(kid)),taskExecutor).join();
  }

  // 法律领域类型
  public String getDomain_type(){
    return CompletableFuture.supplyAsync(() -> ToolClient.queryJson(apiContractTemplateDao.getDomain_type()),taskExecutor).join();
  }

  // 通过合同kid获取文件，返回文件字节流
  public void getContractFile(final Long contractId,final HttpServletResponse response) throws IOException{
    final String loginId = LocalUserId.get();
    HashMap<String,Object> formData = new HashMap<String,Object>(2);
    formData.put("contractId",contractId);
    formData.put("loginId",loginId);
    ServletOutputStream out = response.getOutputStream();
    try{
      boolean b = apiContractOrderService.queryExist(formData);
      if(loginId == null){//token无效或已过期
        response.setStatus(205);
        return;
      }
      if(!b){//尚未购买当前模板
        response.setStatus(203);
        return;
      }
      final long[] list = ToolString.keysToArarry(String.valueOf(contractId));
      final List<HashMap<String,String>> files = apiContractTemplateDao.queryFiles(list);
      if(files == null){//未获取到资源文件
        response.setStatus(202);
        return;
      }
      HashMap<String,String> fileInfo = files.get(0);
      File file = new File(fileInfo.get("contract_file"));
      byte[] fileBytes = FileUtils.readFileToByteArray(file);
      response.setStatus(200);
      response.setCharacterEncoding("utf-8");
      response.setHeader("contract_name",URLEncoder.encode(fileInfo.get("contract_name"),"UTF-8"));
      response.setHeader("category",fileInfo.get("category"));
      out.write(fileBytes);
    }catch(final Exception ignored){
      ignored.printStackTrace();
    }finally{
      out.close();
    }
  }
}